<?php
namespace app\common\model;
use think\Db;
class Wx{
    
    /**
     * 返回微信插件对象
     * @return \my\Wx
     */
    static public function getObj(){
        $wx = new \my\Wx([
            'token'         => self::getToken(),
            'encodingaeskey'=> c('wx_aeskey'),
            'appid'         => c('wx_appid'),
            'appsecret'     => c('wx_secret'),
        ]);
        return $wx;
    }
    
    
    /**
     * 获取微信access_token
     */
    static public function getToken(){
        $appid    = c('type.wx_appid');
        $secret   = c('type.wx_secret');
        $authname = 'wechat_access_token'.$appid;
        $rs       = Db::name('wx_token')->where('name', $authname)->find();
    
        if( !$rs || bcadd($rs['update_time'], $rs['expires_in']) < time() ){
            $wx = new \my\Wx([]);
            $token = $wx->checkAuth($appid, $secret);
        }else{
            $token = $rs['access_token'];
        }
        return $token;
    }
    

    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     * @return openid
     */
    public function GetOpenidFromMp( $code )
    {
        $url= $this->__CreateOauthUrlForOpenid($code);
        $res= file_get_contents($url);
        $data = json_decode($res,true);
        $this->data = $data;
        if(isset($data['errcode']) && $data['errcode']!=0 ) return com_error([$data['errmsg']]);
        $openid = $data['openid'];
        return $openid;
    }
    
    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     * @return 返回构造好的url
     */
    public function CreateOauthUrlForCode( $redirectUrl )
    {
        $d["appid"]         = c('wx_appid');
        $d["redirect_uri"]  = "$redirectUrl";
        $d["response_type"] = "code";
        $d["scope"]         = "snsapi_base";
        $d["state"]         = "STATE"."#wechat_redirect";
        return com_build_url("https://open.weixin.qq.com/connect/oauth2/authorize?", $d, true);
    }
    
    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     * @return 请求的url
     **/
    private function __CreateOauthUrlForOpenid( $code )
    {
        $d["appid"]  = c('wx_appid');
        $d["secret"] = c('wx_secret');
        $d["code"]   = $code;
        $d["grant_type"] = "authorization_code";
        return com_build_url("https://api.weixin.qq.com/sns/oauth2/access_token?", $d, true);
    }
}